import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login'
import Main from "@/views/Main";
import Dept from "@/views/sys/Dept";
import User from "@/views/sys/User";
import Role from "@/views/sys/Role";
import Menu from "@/views/sys/Menu";
import Post from "@/views/sys/Post";
import Course from "@/views/tb/Course";
import Activity from "@/views/tb/Activity";
import axios from "axios"; 
import store from "@/store/index"
import NotFound from "@/views/404";
import Demo from "@/views/stat/Demo";
Vue.use(VueRouter)

const routes = [
  {
    path: "/",
    name: "Login",
    component: Login,
  },
  {
    path: "/login",
    name: "Login",
    component: Login,
  },
  {
    path: "/main",
    name: "Main",
    component: Main,
    children: [
      {
        path: '/dict/data/:dictType',
        name: 'Data',
        component: () => import('@/views/sys/DictData'),
      },
      {
        path: '/clue/details',
        name: 'ClueDetails',
        component:  () => import('@/views/tb/clue/Detail'),
      },
      {
        path: '/clue/follow',
        name: 'ClueFollow',
        component: () => import('@/views/tb/clue/Follow'),
      },
      {
        path: '/business/details',
        name: 'BusinessDetails',
        component:  () => import('@/views/tb/bs/Detail'),
      },
      {
        path: '/business/follow',
        name: 'BusinessFollow',
        component: () => import('@/views/tb/bs/Follow'),
      },
      {
        path: '/contract/details',
        name: 'ContractDetails',
        component: () => import('@/views/tb/contract/Detail'),
      },
      {
        path: "/act/list",
        name: "Demo",
        component: Demo,
      }
    ]
  }
]
// 防止连续点击多次路由报错
let routerPush = VueRouter.prototype.push;
let routerReplace = VueRouter.prototype.replace;
// push
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(err => err)
}
// replace
VueRouter.prototype.replace = function push(location) {
  return routerReplace.call(this, location).catch(err => err)
}
const router = new VueRouter({
  routes
})

// 3. 重置路由的核心方法：用新的matcher替换旧的matcher
export function resetRouter() {
  // 创建一个全新的路由实例（仅含常量路由）
  const newRouter = new VueRouter({
    routes
  })
  // 关键操作：替换matcher，彻底清除动态路由
  router.matcher = newRouter.matcher 
}

//全局路由守卫
router.beforeEach((to,from,next)=>{
  if(to.path=="/login" || to.path=="/"){
    //放行
    next();
  }else{
    //判断是否登录
    let token=store.state.token;
    if(token){
      if(store.state.userInfo.username=='未登录' || router.getRoutes().length<17){//获取用户信息
        axios.get("/api/getInfo")
          .then((res) => {
            if (res.data.code == 200) {
              store.commit("setUserInfo",{
                "username":res.data.username,
                "avatar":res.data.avatar==null?store.state.userInfo.avatar:res.data.avatar,
                "permissions":res.data.permissions
              });
              //保存动态菜单
              store.commit("setMenus",res.data.menus);
              //加载动态路由
              loadDynamicRouters(res.data.menus).forEach((menu=>{
                if(menu.component!=Main){
                  router.addRoute("Main",menu);
                }else{
                  router.addRoute(menu);
                }
              }));
              // 最后添加404路由，确保在所有路由之后
              router.addRoute({ path: "*", name: "NotFound", component: NotFound });
              //刷新
              next({ ...to, replace: true })
            } else {
              this.$message.error(res.data.msg);
            }
          })
        .catch((err) => {
          console.log(err);
        });
      }else{
        next();
      }
    }else{
      Vue.prototype.$message.error("无权访问，请先登录");
      next("/login");
    }
  }
})
//加载动态路由
let loadDynamicRouters=(menus)=>{
  let dynamicRouters=[];
  menus.forEach((menu)=>{
    let myRouter={
      path: menu.path,
      name: menu.menuName
    }
    if(menu.component){
      myRouter.component=require('@/views' + menu.component + '.vue').default;
    }else{
      myRouter.component=Main;
    }

    if(menu.children){
      myRouter.children=loadDynamicRouters(menu.children);
    }
    
    dynamicRouters.push(myRouter);
  })

  return dynamicRouters;
}

router.afterEach(()=>{
  console.log("router.getRoutes()",router.getRoutes());
})
export default router
